/*
 * @Description:
 * @Author: Haor
 * @Date: 2022-03-31 20:37:58
 * @LastEditTime: 2022-08-17 21:31:52
 * @LastEditors: 罗梦豪 757986850@qq.com
 */
import { Injectable } from '@nestjs/common'
import { HttpResTemplate, HttpResult } from "@libs/http.result";
import { UserService } from '../user/user.service'
import { JwtService } from '@nestjs/jwt'
import { AuthLoginDto } from './dto/auth-login.dto'
import { ParamsException, BusinessException } from "@exceptions";
import * as svgCaptcha from 'svg-captcha'
import { CacheService } from "@cache";
import { User } from "@entities/user.entity";

interface ValidataUserParams {
	userName: string
	password: string | number
}
@Injectable()
export class AuthService {
	constructor(
	    private cacheService: CacheService,
	    private userService: UserService,
        private jwtService: JwtService) {
    }

	/**
	 * 用户登录
	 * @param authLogin
	 */
	async login(authLoginDto: AuthLoginDto): Promise<HttpResTemplate> {
		// 通过用户名查找用户是否存在
		const user = await this.userService.getUserByName(authLoginDto.userName)
		const errorMessage = '用户名或密码有误'
		if (!user) {
			throw new BusinessException(errorMessage) //自定义异常
		}

		// 通过用户名称取出用户密码， 备注（忽略加密与数据密文对比步骤）
		const userPassword = await this.userService.getUserPassword({
			userName: authLoginDto.userName
		})

		// 判断密码错误
		if (authLoginDto.password !== userPassword) {
			throw new BusinessException(errorMessage) //自定义异常
		}

        // await this.cacheService.set(`sys_user_${user.id}`, user) //存储用户登录信息

		// 生成token
		const loginResData = {
			accessToken: this.genToken({ userName: user.userName, userId: user.id }),
			info: user
		}
		return HttpResult.success(loginResData)
	}


    /**
     * 退出登录
     * @param userId
     */
	async logout(userId: number): Promise<HttpResTemplate> {
        const findUser = await this.userService.getUserById(userId)
        if (!findUser) {
            throw new ParamsException()
        }
        await this.cacheService.del(`sys_user_${findUser.id}`) //删除用户登录信息
        return HttpResult.success(null, '退出成功')
    }

	// 生成 token
	genToken(payload: any): string {
		const tokenPrefix = `Bearer `
		return `${this.jwtService.sign(payload, {
		    
        })}`
	}

    /**
     * 获取验证码
     */
    getCaptcha() {
        const captcha = svgCaptcha.createMathExpr({
            color: false,
            background: '#cc9966',
            fontSize: 50,
            charPreset: '1+1=2?',
            mathMin: 1,
            mathMax: 9,
            mathOperator: '+'
        })
        console.log(captcha.data)
        return captcha.data

        // const random = randomNumber(4)
        // const captcha = new captchapng(80, 30, random)
        // captcha.color(0, 0, 0, 0);
        // captcha.color(80, 80, 80, 255);
        // const base64 = captcha.getBase64();
        // return HttpResult.success(base64)
    }

	// 刷新 token
	refreshToken(id: number): string {
		return ''
	}

	// 校验 token
	verifyToken(token: string): number {
		return 111
	}

    /**
     * 验证用户
     * @param {string} userName
     * @param {string} password
     */
	async validateUser({ userName, password }: ValidataUserParams): Promise<User> {
        const user: User = await this.userService.getUserByNameAndPassword(userName, "" + password)
		if (!user) {
            throw new BusinessException('用户不存在')
        }
		return user
	}
}
